package com.terrynoya.fight.data.parser.sff
{
	import com.terrynoya.coreLib.MHashMap;
	
	import flash.display.Bitmap;
	import flash.geom.Point;

	/**
	 * @author acer
	 */
	public class SpriteMaker
	{
		private var _sffGroups:MHashMap;
		
		private var _spriteNodeMap:MHashMap;
		
		private var _sffReader:SFFReader;
		
		public function SpriteMaker(sffReader:SFFReader)
		{
			this._sffGroups = new MHashMap();
			this._spriteNodeMap = new MHashMap();
			this._sffReader = sffReader;
			
			var nodesCount:int = sffReader.spriteNodes.length;			
			for (var i : int = 0; i < nodesCount; i++) 
			{
				var spriteNode:SFFSpriteNode = sffReader.spriteNodes[i];
//				this._spriteNodeMap.put(spriteNode.groupNo + "" + spriteNode.itemNo, spriteNode);
				this._spriteNodeMap.put(spriteNode.id, spriteNode);
			}
		}
		
		public function get sprites():Array 
		{
			return this._spriteNodeMap.toArray();
		}

		private function createSprite(spriteNode:SFFSpriteNode) : SpriteItem
		{
			var palette:Palette = this._sffReader.getPalNode(spriteNode.paletteIndex).palette;
			var bitmap:Bitmap = PNG8Maker.make(spriteNode.decode(spriteNode.data), spriteNode.width, spriteNode.height, palette);
			var itemInfo:SpriteItemVO = new SpriteItemVO();
			itemInfo.groupId = spriteNode.groupNo;
			itemInfo.id = spriteNode.itemNo;
			itemInfo.axis = new Point(spriteNode.axisX,spriteNode.axisY);
			var spriteItem:SpriteItem = new SpriteItem(bitmap, itemInfo);
			return spriteItem;
		}


		public function getSprite(groupNo:int,itemNo:int) : SpriteItem
		{
			var group:MHashMap = this.getGroup(groupNo);
			var sprite:SpriteItem;
			var sid:String = groupNo+""+itemNo;
			if(!this._spriteNodeMap.containsKey(sid))
			{
				return null;
			}
			if(!group.containsKey(itemNo))
			{
				var spriteNode:SFFSpriteNode = this._spriteNodeMap.getValue(sid);
				sprite = this.createSprite(spriteNode);
				group.put(sprite.id, sprite);
			}
			sprite = group.getValue(itemNo);
			return sprite;
		}
		
		private function getGroup(groupId:int) : MHashMap
		{
			if(!this._sffGroups.containsKey(groupId))
			{
				this._sffGroups.put(groupId, new MHashMap());
			}
			return this._sffGroups.getValue(groupId);
		}
	}
}
